<template>
  <div>
    <el-card class="form-card">
      <el-form ref="formRef" :inline="true">
        <el-form-item label="时间范围">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          style="margin-right: 16px;width: 15rem"
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          :clearable="false"
                          value-format="YYYY-MM-DD"/>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="content-card" style="margin-bottom: 9px">
      <template #header>
        <span>用户概况</span>
      </template>
      <div class="chart-warp">
        <VChart :loading="loading" :option="chartsOption" autoresize/>
      </div>
    </el-card>

    <div class="region-warp">
      <el-row :gutter="9">
        <el-col :md="12" style="margin-bottom: 9px">
          <el-card class="content-card">
            <template #header>
              <span>用户地域分布</span>
              <div class="card-header-extra">
                <div class="card-header-extra-options hidden-xs-only">
                  <el-link :underline="false" :class="{checked: regionType == 1}" @click="handleSelectRegionType(1)">全部</el-link>
                  <el-link :underline="false" :class="{checked: regionType == 2}" @click="handleSelectRegionType(2)">新增</el-link>
                </div>
              </div>
            </template>
            <VChart :loading="loading" :option="mapOption" autoresize class="echarts-region"/>
          </el-card>
        </el-col>

        <el-col :md="12" style="margin-bottom: 9px">
          <el-card class="content-card">
            <template #header>
              <span>用户地域分布</span>
              <div class="card-header-extra">
              </div>
            </template>

            <el-table v-loading="loading" :data="regionUserData" fit highlight-current-row class="echarts-region">
              <el-table-column align="center" label="Top省份" prop="name" min-width="130" sortable>
              </el-table-column>

              <el-table-column align="center" label="总计用户" prop="value" min-width="120" sortable>
              </el-table-column>

              <el-table-column align="right" header-align="center" label="总占比率" prop="percent" min-width="130" sortable>
                <template #default="scope">
                  <el-progress :stroke-width="9" :percentage="scope.row.percent"/>
                </template>
              </el-table-column>

              <el-table-column align="center" label="新增用户" prop="value2" min-width="120" sortable>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">

import { pickerShortcuts } from '@/utils';
import { computed, onBeforeMount, provide, reactive, ref } from 'vue';
import VChart, { THEME_KEY } from 'vue-echarts';
import useLoading from '@/hooks/use-loading.ts';
import dayjs from 'dayjs';
import '@/utils/echarts.ts'
import { ChartsSeriesData, statisticUserCharts, statisticUserRegion } from '@/api/dashboard.ts';
import { useDark } from '@vueuse/core';

defineOptions({name: 'statistic-user'});

const isDark = useDark();
const eChartTheme = computed(() => (isDark.value ? 'dark' : ''));
provide(THEME_KEY, eChartTheme);

// 查询
const queryFormData = reactive({
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const pickerDate = ref<any[]>([]);
const [loading, setLoading] = useLoading(true);

/** 图表 */
const chartsOption = computed(() => {
  return {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    legend: {
      data: legendData.value,
    },
    toolbox: {
      show: true,
      showTitle: false,
      feature: {
        mark: {show: true},
        magicType: {show: true, type: ['line', 'bar', 'tiled']},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData.value,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: true,
        alignWithLabel: true,
      },
      // axisLabel: {
      //   interval: 0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
      //   rotate: 38   //调整数值改变倾斜的幅度（范围-90到90）
      // }
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    series: seriesData.value,
  };
});

/** 地区 */
const mapOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: function (params: any) {
        return [
          params.name,
          '总计用户：' + (regionType.value == 1 ? params.value || 0 : params['data']?.value2 || 0),
          '新增用户：' + (regionType.value == 2 ? params.value || 0 : params['data']?.value2 || 0),
        ].join('<br>');
      }
    },
    // 左侧小导航图标
    visualMap: {
      show: true,
      min: regionMinNum.value,
      max: regionMaxNum.value,
      text: ['高', '低'],
      color: ['#1a53ff', '#D8FAFE']
      // color: ['#f44336', '#fc9700', '#ffde00', '#ffde00', '#00eaff']
    },
    // 配置属性
    series: [
      {
        type: 'map',
        mapType: 'china',
        roam: true,
        scaleLimit: {
          min: 1.0
        },
        label: {
          normal: {
            show: false // 是否显示省份名称
          },
          emphasis: {
            show: true,
          }
        },
        itemStyle: {
          normal: {
            label: {
              show: true
            },
            borderWidth: .5,
            borderColor: '#1a53ff',

          },
          emphasis: {
            borderWidth: 1,
            borderColor: '#1a53ff',
            shadowColor: '#FC8A4E',
            shadowBlur: 10,
            zoom: 3,
          }
        },
        data: regionSeriesData.value
      }
    ]
  };
});

const legendData = ref<string[]>(['注册人数']);
const xAxisData = ref<string[]>([]);
const seriesData = ref<any[]>([]);

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

onBeforeMount(() => {
  // 重置查询表单
  handleResetQueryForm();
});

/**
 * 数据查询
 */
const fetchDataList = async () => {
  if (!pickerDate.value || pickerDate.value.length != 2) {
    return
  }
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    // 图表统计
    await fetchStatisticUserCharts();
    // 区域统计
    await fetchStatisticUserRegion();
  } catch (err) {
    console.log(err)
  } finally {
    setLoading(false);
  }
};

/**
 * 图表统计
 */
const fetchStatisticUserCharts = async () => {
  try {
    const {data} = await statisticUserCharts(queryFormData);
    legendData.value = data.legend || [];
    xAxisData.value = data.xAxis || [];
    seriesData.value = data.series || [];
  } catch (err) {
    console.log(err)
  }
}

/**
 * 区域统计
 */
const fetchStatisticUserRegion = async () => {
  try {
    const {data} = await statisticUserRegion(queryFormData);
    regionUserData.value = data;
    handleRegionSeriesData();
  } catch (err) {
    console.log(err)
  }
}

// 重置查询条件
const handleResetQueryForm = () => {
  let nowDate = new Date();
  let endTime = dayjs(nowDate).format('YYYY-MM-DD');
  let startTime = dayjs(nowDate.setDate(nowDate.getDate() - 30)).format('YYYY-MM-DD');
  pickerDate.value = [startTime, endTime];
  handleSearch();
};

const regionUserData = ref<ChartsSeriesData[]>([]);
const regionMinNum = ref(0);
const regionMaxNum = ref(100);

const regionType = ref(2);
const regionSeriesData = ref<ChartsSeriesData[]>([]);
const handleSelectRegionType = (item: number) => {
  regionType.value = item;
  handleRegionSeriesData();
};

const handleRegionSeriesData = () => {
  let dataList: ChartsSeriesData[] = [];
  if (regionType.value == 1) {
    // 全国
    regionUserData.value.forEach(item => dataList.push({name: item.name, value: item.value, value2: item.value2}));
  } else {
    // 新增
    regionUserData.value.forEach(item => dataList.push({name: item.name, value: item.value2 || 0, value2: item.value}));
  }
  // 去掉未知地区
  dataList = dataList.filter(it => it.name != '未知');

  let numbers: number[] = [];
  dataList.forEach(it => numbers.push(it.value))
  regionMinNum.value = Math.min(...numbers) || 0;
  regionMaxNum.value = Math.max(...numbers) || 10;

  regionSeriesData.value = dataList;
}
</script>

<style scoped lang="scss">
.chart-warp {
  height: 400px;
  width: 100%;
}

.echarts-region {
  height: 400px;
  width: 100%;
}

:deep() {
  .el-progress__text {
    font-size: var(--el-font-size-base) !important;
  }
}

.card-header-extra {
  margin-right: 1rem;

  .card-header-extra-options {
    > a {
      margin-left: 16px;
    }
  }

  .el-date-editor {
    width: 250px;
  }
}

.el-link {
  &.checked {
    color: var(--el-color-primary)
  }
}

</style>
